import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { mockApi } from '../services/mockApi';
import { api } from '../services/api';
import { DashboardStats } from '../types';
import { 
  Package, 
  Truck, 
  DollarSign, 
  TrendingUp,
  Clock,
  AlertTriangle,
  Star,
  Activity
} from 'lucide-react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell
} from 'recharts';

const mockChartData = [
  { name: '1月', orders: 65, revenue: 520000 },
  { name: '2月', orders: 59, revenue: 475000 },
  { name: '3月', orders: 80, revenue: 640000 },
  { name: '4月', orders: 81, revenue: 648000 },
  { name: '5月', orders: 56, revenue: 448000 },
  { name: '6月', orders: 85, revenue: 680000 },
];

const orderStatusData = [
  { name: '已完成', value: 45, color: '#22c55e' },
  { name: '运输中', value: 25, color: '#3b82f6' },
  { name: '待处理', value: 20, color: '#f59e0b' },
  { name: '异常', value: 10, color: '#ef4444' },
];

interface DashboardProps {
  onNavigate?: (path: string) => void;
}

export const Dashboard: React.FC<DashboardProps> = ({ onNavigate }) => {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const data = await api.analytics.getDashboardStats();
        setStats(data);
      } catch (error) {
        console.error('获取仪表盘数据失败:', error);
        // 使用默认值
        setStats({
          totalOrders: 0,
          pendingOrders: 0,
          completedOrders: 0,
          exceptionOrders: 0,
          totalRevenue: 0,
          totalCost: 0,
          activeVehicles: 0,
          totalVehicles: 0,
          onTimeDeliveryRate: 0.95,
          customerSatisfaction: 4.8,
        });
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, []);

  // 快速操作处理函数
  const handleQuickAction = (actionType: string) => {
    switch (actionType) {
      case 'new_order':
        if (onNavigate) {
          onNavigate('/orders');
        }
        break;
      case 'cargo_management':
        if (onNavigate) {
          onNavigate('/cargo');
        }
        break;
      case 'analytics_report':
        if (onNavigate) {
          onNavigate('/analytics');
        }
        break;
      default:
        console.log('未知操作类型:', actionType);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        {/* Loading skeleton */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="bg-white rounded-xl p-6 animate-pulse">
              <div className="h-4 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="h-8 bg-gray-200 rounded w-1/2"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (!stats) return null;

  const profit = stats.totalRevenue - stats.totalCost;
  const profitMargin = ((profit / stats.totalRevenue) * 100).toFixed(1);

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Welcome Section */}
      <div className="bg-gradient-to-r from-primary-500 via-primary-600 to-secondary-600 rounded-2xl p-8 text-white relative overflow-hidden">
        <div className="absolute top-0 right-0 w-32 h-32 bg-white opacity-10 rounded-full -mr-16 -mt-16"></div>
        <div className="absolute bottom-0 left-0 w-24 h-24 bg-white opacity-10 rounded-full -ml-12 -mb-12"></div>
        <div className="relative">
          <h1 className="text-3xl font-bold mb-2">欢迎回来！</h1>
          <p className="text-primary-100 mb-6">今天是 {new Date().toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            weekday: 'long' 
          })}</p>
          <div className="flex items-center space-x-6">
            <div className="flex items-center space-x-2">
              <Activity className="w-5 h-5" />
              <span className="text-sm">系统运行正常</span>
            </div>
            <div className="flex items-center space-x-2">
              <Star className="w-5 h-5" />
              <span className="text-sm">客户满意度 {stats.customerSatisfaction}/5.0</span>
            </div>
          </div>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">总订单数</p>
                <p className="text-2xl font-bold text-gray-800">{stats.totalOrders}</p>
                <div className="flex items-center mt-2">
                  <TrendingUp className="w-4 h-4 text-success-500 mr-1" />
                  <span className="text-sm text-success-600">+12%</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-primary-500 to-primary-600 rounded-xl flex items-center justify-center">
                <Package className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-primary-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">活跃车辆</p>
                <p className="text-2xl font-bold text-gray-800">{stats.activeVehicles}/{stats.totalVehicles}</p>
                <div className="flex items-center mt-2">
                  <Badge variant="success" size="sm">{Math.round((stats.activeVehicles / stats.totalVehicles) * 100)}% 利用率</Badge>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-secondary-500 to-secondary-600 rounded-xl flex items-center justify-center">
                <Truck className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-secondary-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">总收入</p>
                <p className="text-2xl font-bold text-gray-800">¥{(stats.totalRevenue / 10000).toFixed(1)}万</p>
                <div className="flex items-center mt-2">
                  <span className="text-sm text-success-600">利润率 {profitMargin}%</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-success-500 to-success-600 rounded-xl flex items-center justify-center">
                <DollarSign className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-success-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">准时交付率</p>
                <p className="text-2xl font-bold text-gray-800">{(stats.onTimeDeliveryRate * 100).toFixed(0)}%</p>
                <div className="flex items-center mt-2">
                  <Clock className="w-4 h-4 text-primary-500 mr-1" />
                  <span className="text-sm text-gray-600">本月平均</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-warning-500 to-warning-600 rounded-xl flex items-center justify-center">
                <Clock className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-warning-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Revenue Trend */}
        <Card className="col-span-1">
          <CardHeader>
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-800">收入趋势</h3>
              <Badge variant="info">近6个月</Badge>
            </div>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={mockChartData}>
                <defs>
                  <linearGradient id="revenueGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis dataKey="name" stroke="#64748b" />
                <YAxis stroke="#64748b" />
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: 'white',
                    border: 'none',
                    borderRadius: '12px',
                    boxShadow: '0 10px 40px rgba(0,0,0,0.1)'
                  }}
                  formatter={(value: any) => [`¥${(value / 10000).toFixed(1)}万`, '收入']}
                />
                <Area 
                  type="monotone" 
                  dataKey="revenue" 
                  stroke="#3b82f6" 
                  strokeWidth={3}
                  fill="url(#revenueGradient)" 
                />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Order Status Distribution */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-800">订单状态分布</h3>
              <Badge variant="info">当前</Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex items-center">
              <ResponsiveContainer width="60%" height={250}>
                <PieChart>
                  <Pie
                    data={orderStatusData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={100}
                    paddingAngle={5}
                    dataKey="value"
                  >
                    {orderStatusData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value: any) => [`${value}%`, '占比']} />
                </PieChart>
              </ResponsiveContainer>
              <div className="w-40% pl-6 space-y-3">
                {orderStatusData.map((item, index) => (
                  <div key={index} className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <div 
                        className="w-3 h-3 rounded-full" 
                        style={{ backgroundColor: item.color }}
                      />
                      <span className="text-sm text-gray-600">{item.name}</span>
                    </div>
                    <span className="text-sm font-medium text-gray-800">{item.value}%</span>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions & Alerts */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Quick Actions */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <h3 className="text-lg font-semibold text-gray-800">快速操作</h3>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              {[
                { 
                  label: '新建订单', 
                  icon: Package, 
                  color: 'from-primary-500 to-primary-600',
                  action: 'new_order'
                },
                { 
                  label: '货物管理', 
                  icon: Package, 
                  color: 'from-secondary-500 to-secondary-600',
                  action: 'cargo_management'
                },
                { 
                  label: '数据分析', 
                  icon: TrendingUp, 
                  color: 'from-warning-500 to-warning-600',
                  action: 'analytics_report'
                },
              ].map((action, index) => (
                <button
                  key={index}
                  onClick={() => handleQuickAction(action.action)}
                  className={`
                    bg-gradient-to-br ${action.color} text-white p-4 rounded-xl
                    hover:shadow-lg transform hover:scale-105 transition-all duration-200
                    flex flex-col items-center space-y-2 cursor-pointer
                    focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2
                  `}
                >
                  <action.icon className="w-6 h-6" />
                  <span className="text-sm font-medium">{action.label}</span>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* System Alerts */}
        <Card>
          <CardHeader>
            <div className="flex items-center space-x-2">
              <AlertTriangle className="w-5 h-5 text-warning-500" />
              <h3 className="text-lg font-semibold text-gray-800">系统提醒</h3>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-start space-x-3 p-3 bg-error-50 rounded-lg border border-error-200">
              <div className="w-2 h-2 bg-error-500 rounded-full mt-2 flex-shrink-0"></div>
              <div>
                <p className="text-sm font-medium text-error-800">{stats.exceptionOrders} 个异常订单</p>
                <p className="text-xs text-error-600">需要及时处理</p>
              </div>
            </div>
            
            <div className="flex items-start space-x-3 p-3 bg-warning-50 rounded-lg border border-warning-200">
              <div className="w-2 h-2 bg-warning-500 rounded-full mt-2 flex-shrink-0"></div>
              <div>
                <p className="text-sm font-medium text-warning-800">3 辆车需要保养</p>
                <p className="text-xs text-warning-600">即将到期</p>
              </div>
            </div>
            
            <div className="flex items-start space-x-3 p-3 bg-success-50 rounded-lg border border-success-200">
              <div className="w-2 h-2 bg-success-500 rounded-full mt-2 flex-shrink-0"></div>
              <div>
                <p className="text-sm font-medium text-success-800">系统运行正常</p>
                <p className="text-xs text-success-600">所有服务正常</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};